import { _decorator, Component, director, macro, math, Node, sys, view } from 'cc'
import { GameEvent } from '../event/gameEvent'
import { VirtualInput } from '../ui/VirtualInput'
import { Actor } from './Actor'
import { AimDirection } from './AimDirection'
import { SimpleEmitter } from './projectile/SimpleEmitter'
import { Die } from './state/Die'
import { Idle } from './state/Idle'
import { Run } from './state/Run'
import { StateDefine } from './StateDefine'
const { ccclass, property, requireComponent } = _decorator

@ccclass('PlayerController')
@requireComponent(Actor) // 确保这个组件必须挂载在Actor上
export class PlayerController extends Component {
    actor: Actor | null = null
    @property(Node)
    aim: Node

    @property(Node)
    gun: Node | null = null;

    @property(SimpleEmitter)
    projectileEmitter: SimpleEmitter = null
    static instance: PlayerController = null
    protected onLoad(): void {

        // 检查是否为iOS平台
        if (sys.os === sys.OS.IOS) {
            // 监听屏幕尺寸变化事件
            view.on('design-resolution-changed', this.setLandscape, this)
            // 初始化时尝试设置横屏
            this.setLandscape()
        }

        // view.setOrientation(macro.ORIENTATION_LANDSCAPE)
    }
    setLandscape() {
        // 设置横屏
        // var isLandscape = view.isLandscape()

        // 请求更改方向为横屏
        view.setOrientation(macro.ORIENTATION_LANDSCAPE_LEFT)
        // view.resizeWithBrowserSize(true)
        // let canvasNode = find('LevelCanvas')
        // let { width, height } = view.getFrameSize()
    }
    start() {

        PlayerController.instance = this
        this.actor = this.node.getComponent(Actor)
        console.log(this.actor, 'this.actor player')
        console.log(this.projectileEmitter, 'this.projectileEmitter player')
        // 注册角色状态
        this.actor.stateMgr.registState(new Idle(StateDefine.Idle, this.actor))
        this.actor.stateMgr.registState(new Run(StateDefine.Run, this.actor))
        this.actor.stateMgr.registState(new Die(StateDefine.Die, this.actor))
        this.actor.stateMgr.startWith(StateDefine.Idle)
        this.projectileEmitter.actor = this.actor
        director.on(GameEvent.OnFireButtonClicked, (dir) => {
            this.fire(dir)
        })

    }

    update(deltaTime: number) {
        if (this.actor.dead) {
            return
        }
        let { horizontal: h, vertical: v } = VirtualInput
        this.actor.input.set(h, v)
        // console.log(this.actor.input.length(), math.EPSILON)
        if (this.actor.input.length() >= math.EPSILON) {
            this.actor.stateMgr.transit(StateDefine.Run)
        } else {
            this.actor.stateMgr.transit(StateDefine.Idle)
        }
    }

    fire(dir: AimDirection) {
        this.gun?.setWorldRotationFromEuler(0, 0, dir)
        this.projectileEmitter?.emit()
    }
}

